//
//  FavirteViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-10-3.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "FavirteViewController.h"
#import "CameraManCell.h"

#import "TaoCanDetailViewController.h"

@interface FavirteViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *userID;
}
@end

@implementation FavirteViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isCollection = YES;
//    NSArray *segArray = @[@"收藏的套餐",@"收藏的摄影师"];
//    segView = [[UISegmentedControl alloc]initWithItems:segArray];
//    segView.frame = CGRectMake((UI_SCREEN_WIDTH - 180)/2, self.leftBtn.frame.origin.y+7, 180, 30);
//    segView.selectedSegmentIndex = 0;
//    segView.tintColor = [UIColor whiteColor];
//    
//    [segView addTarget:self action:@selector(segViewPressed) forControlEvents:UIControlEventValueChanged];
//    [self.navigationBarView addSubview:segView];
    
    self.titleLabel.text = @"我的收藏";
    
    //摄影师tableview
    layoutTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    layoutTableView.delegate = self;
    layoutTableView.dataSource = self;
    layoutTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    layoutTableView.backgroundColor = [UIColor clearColor];
    [layoutTableView addFooterWithTarget:self action:@selector(footerPulltoRefreshData)];
    [layoutTableView addHeaderWithTarget:self action:@selector(heaererPulltoRefreshData)];
    [self.contentView addSubview:layoutTableView];
    
//    //作品的CollectionView
//    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    flowLayout.minimumInteritemSpacing =0;
//    flowLayout.minimumLineSpacing =3;
//    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
//    mCollectionView = [[UICollectionView alloc] initWithFrame:self.contentView.bounds collectionViewLayout:flowLayout];
//    [mCollectionView registerClass:[favCell class] forCellWithReuseIdentifier:@"cell"];
//    mCollectionView.backgroundColor = mClearColor;
//    mCollectionView.alwaysBounceVertical = YES;
//    mCollectionView.delegate = self;
//    mCollectionView.dataSource = self;
//    mCollectionView.hidden = NO;
//    [self.contentView addSubview:mCollectionView];
//    [mCollectionView addFooterWithTarget:self action:@selector(footerPulltoRefreshCollectionData)];
//    [mCollectionView addHeaderWithTarget:self action:@selector(heaererPulltoRefreshCollectionData)];
    
    
    _ListArray = [[NSMutableArray alloc]init];
    _ListCollectionArray = [[NSMutableArray alloc]init];
    
    userID = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
    
//    curpageCollection = 1;
    curpage = 1;
//    [self initCollectionData:1];
    
    
    //请求数据
    [self initFavData:1];

    
    noDataIV = [[UIImageView alloc] initWithFrame:CGRectMake((UI_SCREEN_WIDTH-111)/2, (UI_MAINSCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT - 78)/2, 111, 78)];
    noDataIV.image = [UIImage imageNamed:@"noData"];
    [self.contentView addSubview:noDataIV];
    noDataIV.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====表格代理====
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_ListArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * bgView = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 10) andBackGroudColor:[UIColor clearColor]];
    return bgView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellid = @"cellid";

    CameraManCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (!cell) {
        cell = [[CameraManCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
    }
    
    NSDictionary * dict = _ListArray[indexPath.row];
    
    [cell initViewsWithDict:dict];
    
    return  cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   [tableView performSelector:@selector(deselectRowAtIndexPath:animated:) withObject:indexPath afterDelay:.5];
    if (IS_NOT_EMPTY([[_ListArray objectAtIndex:indexPath.row] objectForKey:@"EmplID"])) {
        CameraManDetailViewController  *cameraMan = [[CameraManDetailViewController alloc]init];
        cameraMan.cameraManID = [[_ListArray objectAtIndex:indexPath.row] objectForKey:@"EmplID"];
        cameraMan.type = 1;
        if ([[_ListArray objectAtIndex:indexPath.row][@"IsAuthen"] intValue]) {
            cameraMan.isRenZheng = YES;
        }else{
            cameraMan.isRenZheng = NO;
        }
        [self.navigationController pushViewController:cameraMan animated:YES];
    }

}


//#pragma mark UICollectionView Delegate
////设置分区
//-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return 1;
//}
//
////每个分区上的元素个数
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
//{
//    return [_ListCollectionArray count];
//}
//
////设置元素内容
//- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *identify = @"cell";
//    favCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
//    cell.dataDict = [_ListCollectionArray objectAtIndex:indexPath.row];
//    return cell;
//}
//
////设置元素的的大小框
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    UIEdgeInsets top ={3,3,3,3};
//    return top;
//}
//
////设置顶部的大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    CGSize size={0,0};
//    return size;
//}
//
////设置元素大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake(155.5,210);
//}
//
////点击元素触发事件
//-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSDictionary * dict = [_ListCollectionArray objectAtIndex:indexPath.row];
//    TaoCanDetailViewController * taocanVC = [[TaoCanDetailViewController alloc] init];
//    taocanVC.SeriesID = dict[@"SeriesID"];
//    taocanVC.EmplID = dict[@"EmplID"];
//    taocanVC.SceneID = dict[@"SceneID"];
//    taocanVC.sceneName = dict[@"SceneName"];
//    taocanVC.SeriesName = dict[@"SeriesName"];
//    taocanVC.type = 1;
//    
//    
//    //值的存储 -- 摄影师
//    [XDTools sharedXDTools].emplImgUrl = dict[@"EmplAvator"];
//    [XDTools sharedXDTools].emplLevel = dict[@"LevelName"];
//    [XDTools sharedXDTools].emplName = dict[@"EmplName"];
//    
//    if(ARRAY_IS_NOT_EMPTY(dict[@"ReviewTypeAvg"])){
//        
//        [XDTools sharedXDTools].emplZhuanYe = [[dict[@"ReviewTypeAvg"] firstObject] valueForKey:@"Avg"];
//        [XDTools sharedXDTools].emplGouTong =[[dict[@"ReviewTypeAvg"] objectAtIndex:1] valueForKey:@"Avg"];
//        [XDTools sharedXDTools].emplShoushi =[[dict[@"ReviewTypeAvg"] lastObject] valueForKey:@"Avg"];
//        
//    }else{
//        [XDTools sharedXDTools].emplZhuanYe = nil;
//        [XDTools sharedXDTools].emplGouTong =nil;
//        [XDTools sharedXDTools].emplShoushi =nil;
//    }
//
//    
//    [self.navigationController pushViewController:taocanVC animated:YES];
//}
//
//
//-(void)footerPulltoRefreshCollectionData
//{
//    isGetMoreCollection = YES;
//    if (curpageCollection < totalPageCollection) {
//        curpageCollection++;
//        [self initCollectionData:curpageCollection];
//    }else{
//        if (curpageCollection == totalPageCollection) {
//            mCollectionView.footerRefreshingText = @"没有更多订单...";
//            [self performSelector:@selector(delayToEndRefreshLoading) withObject:nil afterDelay:.8f];
//        }
//    }
//}
//-(void)heaererPulltoRefreshCollectionData
//{
//    curpageCollection = 1;
//  
//    [self initCollectionData:curpageCollection];
// 
//    isGetMoreCollection = NO;
//}
#pragma mark  =======UITableView上下拉刷新========
-(void)footerPulltoRefreshData
{
    isGetMore = YES;
    if (curpage < totalPage) {
        curpage++;
        [self initFavData:curpage];
    }else{
        if (curpage == totalPage) {
//            layoutTableView.footerRefreshingText = @"没有更多订单...";
            [self performSelector:@selector(delayToEndRefreshLoading) withObject:nil afterDelay:.8f];
        }
    }
}
-(void)heaererPulltoRefreshData
{
    curpage = 1;
    [self initFavData:curpage];
    isGetMore = NO;
}
-(void)delayToEndRefreshLoading
{
    [layoutTableView footerEndRefreshing];
    [mCollectionView footerEndRefreshing];
    layoutTableView.footerRefreshingText = @"正在加载数据";
}
-(void)initCollectionData:(int)curPage
{
    //    noDatasView.hidden = YES;
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
    noDataIV.hidden = YES;
    
    NSDictionary *requestDic = @{@"CustomerID":userID,
                                 @"type":@"opus",
                                 @"page":[NSString stringWithFormat:@"%d",curPage],
                                 @"pageSize":@"10"};
    
    ASIHTTPRequest *request = [XDTools getRequestWithDict:requestDic API:API_USER_COLLECT];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        
        [mCollectionView footerEndRefreshing];
        [mCollectionView headerEndRefreshing];
        
        NSDictionary *resultDic = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDic);
        if ([[resultDic objectForKey:@"status"] intValue]==1) {
            //                [XDTools showTips:[requestDic objectForKey:@"msg"] toView:self.contentView];
            if ([[resultDic allKeys]containsObject:@"data"]) {
                if (!isGetMoreCollection) {
                    [_ListCollectionArray removeAllObjects];
                }
                
                [_ListCollectionArray  addObjectsFromArray:[[[resultDic objectForKey:@"data"] objectForKey:@"List"] mutableCopy]];
                
                [mCollectionView reloadData];
                
                if ([[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]%10==0) {
                    totalPageCollection = [[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]/10;
                }else{
                    totalPageCollection = [[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]/10+1;
                }
                if (_ListCollectionArray.count) {
                    noDataIV.hidden = YES;
                }else{
                    noDataIV.hidden = NO;
                }
            }else{
                noDataIV.hidden = NO;
//                [XDTools showTips:[resultDic objectForKey:@"msg"] toView:self.view];
            }
            
        }else{
            [XDTools showTips:[resultDic objectForKey:@"msg"] toView:self.view];
        }
        
    }];
    [request setFailedBlock:^{

        [mCollectionView footerEndRefreshing];
        [mCollectionView headerEndRefreshing];
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
            
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
    
}

-(void)initFavData:(int)curPage
{
//    noDatasView.hidden = YES;
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }
//xD8179395FF064708AC2B64E17E166B26x
//    Lat = "40.057010";
//    Lng = "116.411795";
//    NSDictionary *requestDic = @{@"Lat":@"40.057010",@"Lng":@"116.411795",@"page":[NSString stringWithFormat:@"%d",curpage],@"pageSize":@10};
    
    NSDictionary * requestDic = @{@"CustomerID":userID,
                                  @"Type":@"people",
                                  @"page":[NSString stringWithFormat:@"%d",curPage],
                                  @"pageSize":@"10"};

    ASIHTTPRequest *request = [XDTools getRequestWithDict:requestDic API:API_USER_COLLECT];
    
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        
        [layoutTableView footerEndRefreshing];
        [layoutTableView headerEndRefreshing];
        
        NSDictionary *resultDic = [XDTools JSonFromString:[mrequest responseString]];
        DDLOG(@"res....%@",resultDic);
        if ([[resultDic objectForKey:@"status"] intValue]==1) {
            //                [XDTools showTips:[requestDic objectForKey:@"msg"] toView:self.contentView];
            if ([[resultDic allKeys]containsObject:@"data"]) {
                if (!isGetMore) {
                    [_ListArray removeAllObjects];
                }
                
             [_ListArray  addObjectsFromArray:[[[resultDic objectForKey:@"data"] objectForKey:@"List"] mutableCopy]];
                
                [layoutTableView reloadData];
//                [mCollectionView reloadData];
                
                if ([[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]%10==0) {
                    totalPage = [[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]/10;
                }else{
                    totalPage = [[[resultDic objectForKey:@"data"] objectForKey:@"Count"] intValue]/10+1;
                }
                if (_ListArray.count) {
                    noDataIV.hidden = YES;
                }else{
                    noDataIV.hidden = NO;
                }
            }else{
                noDataIV.hidden = NO;
//                [XDTools showTips:[resultDic objectForKey:@"msg"] toView:self.view];
            }
            
        }else{
            [XDTools showTips:[resultDic objectForKey:@"msg"] toView:self.view];
            [layoutTableView footerEndRefreshing];
            [layoutTableView headerEndRefreshing];
        }
        
    }];
    [request setFailedBlock:^{
        [layoutTableView headerEndRefreshing];
        [layoutTableView footerEndRefreshing];
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
            
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
    
}

-(void)segViewPressed
{
    noDataIV.hidden = YES;
    if (segView.selectedSegmentIndex == 0) {
        isCollection = YES;
        if (_ListCollectionArray.count == 0) {
            [self initCollectionData:1];
        }
        layoutTableView.hidden = YES;
        mCollectionView.hidden = NO;
    }else if (segView.selectedSegmentIndex == 1){
        isCollection = NO;
        if (_ListArray.count == 0) {
            [self initFavData:1];
        }
        layoutTableView.hidden = NO;
        mCollectionView.hidden = YES;
    }
}

@end
